package com.xindaoapp.happypet.fragments;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.ExchangeResult;
import com.xindaoapp.happypet.bean.GoodsRecord;
import com.xindaoapp.happypet.ui.BaseFragment;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 我的兑换明细
 * 
 * 
 */
public class DuihuanDetailFragment extends BaseFragment {

    /**
     * 
     * @param fid
     * @param isBack 是否点击之后返回
     * @return
     */

    public static Fragment newInstance() {
        Fragment fragment = new DuihuanDetailFragment();
        Bundle bundle = new Bundle();
        // bundle.putString(Constants.KEY_GROUP_FID, fid);
        // bundle.putBoolean(Constants.KEY_IS_CLICK_TO_BACK, isBack);
        fragment.setArguments(bundle);
        return fragment;
    }

    private PullToRefreshListView vPullToRefreshListView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_duihuandetail, container, false);
        vPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.listview);
        vPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        vPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadDatas();
            }
        });

    }


    @Override
    protected void loadDatas() {
        super.loadDatas();


        /**
         * 我的兑换记录
         */
        getMoccaApi().getGoodsRecord(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<List<GoodsRecord>>() {

                    @Override
                    public void request(List<GoodsRecord> t) {
                        if (t != null) {
                            onDataArrived(true);
                            if (t.size() == 0) {
                                onDataArrivedEmpty();
                            } else {
                                vPullToRefreshListView.setAdapter(new DuihuanDetailAdapter(
                                        getActivity(), t, Constants.PAGE_SIZE,
                                        R.layout.item_myrecord_duihuan, R.layout.item_loading));
                            }
                        } else {
                            onDataArrived(false);
                        }
                        vPullToRefreshListView.onRefreshComplete();
                    }
                });


    }



    /**
     * 我的兑换明细
     * 
     * 
     */
    class DuihuanDetailAdapter extends XinDaoBaseAdapter<GoodsRecord> {


        public DuihuanDetailAdapter(Context context, List<GoodsRecord> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
            // TODO Auto-generated constructor stub
        }



        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<GoodsRecord> iLoadNextPageData) {
            // TODO Auto-generated method stub
            super.nextPage(start, size, iLoadNextPageData);
            /**
             * 兑换商品记录
             */
            HappyPetApplication.get().getMoccaApi()
                    .getGoodsRecord(start, size, new IRequest<List<GoodsRecord>>() {
                        @Override
                        public void request(List<GoodsRecord> t) {
                            iLoadNextPageData.loadNextPageData(t == null ? null : t);
                        }
                    });

        }

        // @Override
        // protected List<GoodsRecord> parseResult(List<GoodsRecord> list) {
        // for (int i = list.size() - 1; i >= 0; i--) {
        // if (getResult().contains(list.get(i))) {
        // list.remove(list.get(i));
        // }
        // }
        // return list;
        // }



        @Override
        public View getView(int position, View convertView, ViewGroup parent,
                final GoodsRecord goods) {
            // TODO Auto-generated method stub
            ViewHolder holder = (ViewHolder) convertView.getTag();

            if (holder == null) {
                holder = new ViewHolder();
                // holder.tv_line = (TextView) convertView.findViewById(R.id.tv_line);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_jifen = (TextView) convertView.findViewById(R.id.tv_jifen);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_status = (TextView) convertView.findViewById(R.id.tv_status);
                convertView.setTag(holder);
            }


            // if (position == 0) {
            // holder.tv_line.setVisibility(View.VISIBLE);
            // }


            ImageLoader.getInstance().displayImage(goods.goods_thumb, holder.icon);
            holder.tv_name.setText(goods.goods_name);
            holder.tv_jifen.setText(goods.exchange_integral + "尾巴币");
            holder.tv_time.setText(goods.updatetime);

            holder.tv_status.setText(goods.exchangetitle);


            convertView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View arg0) {
                    // TODO Auto-generated method stub
                    if ("已取消".equals(goods.exchangetitle)) {
                        return false;
                    }
                    new AlertDialog.Builder(mContext).setTitle("温馨提示").setMessage("确定取消兑换本商品么 ?")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();

                                    HappyPetApplication
                                            .get()
                                            .getMoccaApi()
                                            .getQuxiaoExchangeResult(goods.integral_id,
                                                    new IRequest<ExchangeResult>() {

                                                        @Override
                                                        public void request(ExchangeResult t) {
                                                            // TODO Auto-generated method stub
                                                            if (null != t) {
                                                                if (t.result.equals("0")) {
                                                                    Toast.makeText(
                                                                            mContext.getApplicationContext(),
                                                                            t.msg,
                                                                            Toast.LENGTH_SHORT)
                                                                            .show();


                                                                    CommonUtil
                                                                            .refurshWeiba(mContext);
                                                                    // 刷新页面
                                                                    loadDatas();


                                                                } else {
                                                                    Toast.makeText(
                                                                            mContext.getApplicationContext(),
                                                                            t.msg,
                                                                            Toast.LENGTH_SHORT)
                                                                            .show();
                                                                }
                                                            } else {

                                                                try {
                                                                    Toast.makeText(
                                                                            mContext.getApplicationContext(),
                                                                            R.string.net_error,
                                                                            Toast.LENGTH_SHORT)
                                                                            .show();
                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }

                                                    });
                                }
                            }).create().show();
                    return false;
                }
            });



            return convertView;

        }

        class ViewHolder {
            ImageView icon;
            TextView tv_jifen, tv_status, tv_name, tv_time, tv_line;

        }

    }

}
